package myJs.cps

import cats.effect.SyncIO
import myJs.Implicits._
import myJs.myPkg.reactHookForm._
import myJs.tool.Tool.messages
import japgolly.scalajs.react.vdom.all._
import japgolly.scalajs.react._
import japgolly.scalajs.react.React.Fragment
import japgolly.scalajs.react.util.EffectCatsEffect._
import myJs.myPkg.Hooks._
import myJs.Utils._

/** Created by yz on 3/11/2020
  */
object ToggleInlineCp {

  case class Props(
      show: Boolean = true,
      name: String = "",
      value: Boolean,
      valueChange: Boolean => SyncIO[Unit],
      label: String = "",
      questionInfo: String = "",
      inputWidth:Int=8,
      labelWidth:Int=2,
      canChange:SyncIO[Boolean]=SyncIO(true)
  ) {
    @inline def render: VdomElement = {
      Component(this)
    }
  }

  val Component = ScalaFnComponent[Props] { props =>
    val useForm = ReactHookForm.useFormContext()
    object FTool {}

    useEffect(
      {
        if (!props.show) {
          useForm.setValue(props.name, false)
          props.valueChange(false)
        } else SyncIO {}
      },
      List(props.show)
    )

    val displayStr = if (props.show) "block" else "none"
    div(
      display := displayStr,
      className := "form-group",
      label(
        className := s"control-label col-sm-${props.labelWidth}",
        s"${props.label}",
        if (props.questionInfo.nonBlank) {
          span(
            className := "",
            a(
              `type` := "button",
              className := "selfQuestion",
              title := messages("note"),
              dataContainer := "body",
              dataToggle := "popover",
              dataHtml := "true",
              dataPlacement := "left",
              dataContent := props.questionInfo,
              dataTrigger := "hover",
              i(className := "fa fa-question-circle-o")
            )
          )
        } else EmptyVdom,
        ":"
      ),
      div(
        className := s"col-sm-${props.inputWidth} toggling",
        PureToggleCp
          .Props(
            name = props.name,
            value = props.value,
            valueChange = props.valueChange,
            canChange = props.canChange
          )
          .render
      )
    )
  }

}
